import {
  HttpCode,
  HttpException,
  HttpStatus,
  Inject,
  Injectable,
} from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { ResultData } from 'src/utils/result';

@Injectable()
export class ChatroomService {
  @Inject(PrismaService)
  private prismaService: PrismaService;
  async createOneToOneChatroom(friendId: number, userId: number) {
    const friend = await this.prismaService.user.findUnique({
      where: {
        id: friendId,
      },
    });
    if (!friend) {
      throw new HttpException('好友不存在', HttpStatus.BAD_REQUEST);
    }

    const { id } = await this.prismaService.chatroom.create({
      data: {
        name: '聊天室' + Math.random().toString().slice(2, 8),
        type: false,
      },
      select: {
        id: true,
      },
    });
    await Promise.all([
      await this.prismaService.userChatroom.create({
        data: {
          userId,
          chatroomId: id,
        },
      }),
      await this.prismaService.userChatroom.create({
        data: {
          userId: friendId,
          chatroomId: id,
        },
      }),
    ]);

    return 'success';
  }

  async createGroupChatroom(name: string, userId: number) {
    const newChatRoom = await this.prismaService.chatroom.create({
      data: {
        name,
        type: true,
      },
      select: {
        id: true,
      },
    });

    await this.prismaService.userChatroom.create({
      data: {
        chatroomId: newChatRoom.id,
        userId,
      },
    });

    return 'success';
  }

  async list(userId: number) {
    const result = await this.prismaService.userChatroom.findMany({
      where: {
        userId,
      },
      select: {
        chatroomId: true,
      },
    });

    const chatroomList = await this.prismaService.chatroom.findMany({
      where: {
        id: {
          in: result.map((item) => item.chatroomId),
        },
      },
      select: {
        id: true,
        name: true,
        type: true,
        createTime: true,
      },
    });
    let arr = [];
    let newArr = [];
    chatroomList.forEach(async (item) => {
      arr.push(
        (async () => {
          const user = await this.prismaService.userChatroom.findMany({
            where: {
              chatroomId: item.id,
            },
            select: {
              userId: true,
            },
          });
          let flatArr: any = user.map((ok) => ok.userId);
          const template = [];
          for (let i = 0; i < flatArr.length; i++) {
            template.push({
              ...(await this.prismaService.user.findUnique({
                where: {
                  id: flatArr[i],
                },
                select: {
                  createTime: true,
                  email: true,
                  id: true,
                  headPic: true,
                  nickName: true,
                },
              })),
            });
          }
          newArr.push({
            ...item,
            ooo: template,
          });
          return user;
        })(),
      );
    });
    await Promise.all(arr);
    return newArr;
  }

  async members(chatroomId: number) {
    const result = await this.prismaService.userChatroom.findMany({
      where: {
        chatroomId,
      },
    });

    const members = await this.prismaService.user.findMany({
      where: {
        id: {
          in: result.map((item) => item.userId),
        },
      },
      select: {
        id: true,
        createTime: true,
        username: true,
        nickName: true,
        headPic: true,
        email: true,
      },
    });
    return members;
  }

  async info(id: number) {
    const result = await this.prismaService.chatroom.findUnique({
      where: {
        id,
      },
      select: {
        id: true,
        name: true,
        type: true,
        createTime: true,
        updateTime: true,
      },
    });
    if (!result) {
      throw new HttpException('群聊不存在', HttpStatus.NOT_FOUND);
    }
    let vo = {};
    const users = await this.prismaService.userChatroom.findMany({
      where: {
        chatroomId: result.id,
      },
    });
    const flatArr = users.map((item) => item.userId);
    const userDetailList = await this.prismaService.user.findMany({
      where: {
        id: {
          in: flatArr,
        },
      },
      select: {
        createTime: true,
        email: true,
        id: true,
        headPic: true,
        updateTime: true,
        username: true,
      },
    });
    vo = {
      ...result,
      users: userDetailList,
    };
    return ResultData.ok(vo);
  }

  async join(id, joinId) {
    const chatroom = await this.prismaService.chatroom.findUnique({
      where: {
        id,
      },
    });
    if (!chatroom) {
      throw new HttpException('会议室不存在', HttpStatus.BAD_REQUEST);
    }

    if (chatroom.type === false) {
      throw new HttpException('一对一聊天室不能加人', HttpStatus.BAD_REQUEST);
    }

    const record = await this.prismaService.userChatroom.findFirst({
      where: {
        chatroomId: id,
        userId: joinId,
      },
    });
    if (record) {
      throw new HttpException(`当前已在会议室`, HttpStatus.BAD_REQUEST);
    }

    await this.prismaService.userChatroom.create({
      data: {
        userId: joinId,
        chatroomId: id,
      },
    });
    return ResultData.ok('加入成功');
  }

  async quit(id, userId) {
    const chatroom = await this.prismaService.chatroom.findUnique({
      where: {
        id,
      },
    });
    if (!chatroom) {
      throw new HttpException(`会议室不存在`, HttpStatus.BAD_REQUEST);
    }
    if (chatroom.type === false) {
      throw new HttpException(`一对一聊天室不能退出`, HttpStatus.BAD_REQUEST);
    }

    await this.prismaService.userChatroom.deleteMany({
      where: {
        chatroomId: id,
        userId,
      },
    });
    return ResultData.ok('退出成功');
  }
}
